package io.argin.controller;

import io.argin.pojo.Emp;
import io.argin.service.QueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class EmpController {
    @Autowired
    private QueryService service;

    @GetMapping("/insert")
    public ModelAndView insertEmp(ModelAndView mv) {
        mv.addObject("ds",service.listDepts());
        mv.setViewName("insert");
        return mv;
    }

    @PostMapping("/insert")
    public String insertEmp(Emp emp) {
        service.insertEmp(emp);
        return "redirect:/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteEmp(@PathVariable Integer id) {
        service.deleteEmp(id);
        return "redirect:/list";
    }

    @GetMapping("/update/{id}")
    public ModelAndView updateEmp(@PathVariable Integer id, ModelAndView mv) {
        mv.addObject("ds",service.listDepts());
        mv.addObject("emp", service.getEmp(id));
        mv.setViewName("update");
        return mv;
    }

    @PostMapping("/update")
    public String updateEmp(Emp emp) {
        service.updateEmp(emp);
        return "redirect:/list";
    }

    @GetMapping("/list")
    public ModelAndView listEmps(ModelAndView mv) {
        mv.addObject("list", service.listEmps(null));
        mv.setViewName("list");
        return mv;
    }

    @GetMapping("/list/{name}")
    public ModelAndView listEmpsByName(@PathVariable String name, ModelAndView mv) {
        mv.addObject("list", service.listEmps(name));
        mv.addObject("name", name);
        mv.setViewName("list");
        return mv;
    }


}
